<template>
  <div class="tab_class">
    <div class="tal_class_searchBox">
      <van-search placeholder="点击前往搜索" background="#00CC66"/>
      <div class="tal_class_searchMask" @click="$router.push({ name: 'search' })"></div>
    </div>
    <class-tree v-if="list.length" @class-click="toItemList" @all-click="toItemList" :list="list"></class-tree>

    <is-empty v-if="isEmpty">抱歉,店主还未上架商品</is-empty>
  </div>
</template>

<script>
import { GOODS_CATEGORY } from "@/api/goods";

import { Search } from "vant";
import classTree from "./tabbar-class-tree";
import IsEmpty from "@/vue/components/is-empty/";

export default {
  data() {
    return {
      list: [],
      isEmpty: false
    };
  },

  created() {
    this.initData();
  },

  methods: {
    initData() {
      this.$reqGet(GOODS_CATEGORY).then(res => {
        const data = this.makeTree(res.data.data);
        this.list = data;
        this.isEmpty = !data || !data.length;
      });
    },
    makeTree(data) {
      let tree = {};

      data.forEach(item => {
        if (
          item.enabled &&
          (item.type === 2 || item.type === 0) &&
          item.status === 1
        ) {
          tree[item.id] = item;
        }
      });

      data.forEach(item => {
        if (
          item.enabled &&
          (item.type === 2 || item.type === 0) &&
          item.status === 1 &&
          item.parentid > 0
        ) {
          let parent = tree[item.parentid];

          if (parent) {
            if (!parent.children) {
              parent.children = [];
            }

            parent.children.push(item);
          }
        }
      });

      return data.filter(
        item =>
          item.parentid === 0 &&
          (item.enabled &&
            (item.type === 2 || item.type === 0) &&
            item.status === 1)
      );
    },
    toItemList(id = "", name) {
      this.$router.push({
        name: "list",
        query: { category: name, itemClass: id }
      });
    }
  },
  components: {
    [Search.name]: Search,
    [classTree.name]: classTree,
    [IsEmpty.name]: IsEmpty
  }
};
</script>


<style scoped>
.tab_class {
  background-color: #fff;
}

.tal_class_searchBox {
  width: 100%;
  position: relative;
}

.tal_class_searchMask {
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9;
  position: absolute;
}
</style>
